<template>
  <div class="category">
    <h1>{{ id ? "编辑" : "新增" }}文章</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="文章分类:">
        <el-select v-model="form.categories" multiple>
          <el-option
            v-for="item in parents"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="新闻标题:">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="新闻内容:">
        <vue-editor v-model="form.content" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  components: {
    VueEditor
  },
  props: {
    id: String
  },
  data() {
    return {
      form: {},
      parents: []
    };
  },
  created() {
    this.id && this.fetch();
    this.fetchCategory();
  },
  methods: {
    // 富文本框自定义上传图片
   async handleImageAdded(file, Editor, cursorLocation, resetUploader){
    var formData = new FormData();
      formData.append("file", file);
      const {data:{url}} = await this.$http.post('/upload',formData)
      console.log(url,'----');
      Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
   },
    // 获取
    async fetch() {
      const res = await this.$http.get(`/rest/articles/${this.id}`);
      this.form = res.data;
    },
    async fetchCategory() {
      const res = await this.$http.get(`/rest/categories`);
      this.parents = res.data;
    },
    async save() {
      let res;
      if (this.id) {
        res = await this.$http.put(`/rest/articles/${this.id}`, this.form);
      } else {
        res = await this.$http.post("/rest/articles", this.form);
      }
      const { data } = res;
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.push("/articles/list");
      }
    }
  }
};
</script>

<style></style>
